package com.ruoyi.picture.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.picture.service.QiniuService;
import com.ruoyi.picture.utils.QiniuUtil;
import com.ruoyi.system.domain.SystemConfig;
import com.ruoyi.system.service.ISystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 七牛云服务
 * @author lixin
 * @date 2021-05-31 22:55
 */
@Slf4j
@Service
public class QiniuServiceImpl implements QiniuService {

	@Autowired
	private ISystemConfigService systemConfigService;

	@Autowired
	private QiniuUtil qiniuUtil;

	/**
	 * 多文件上传
	 * @param multipartFileList
	 * @return 文件url列表
	 */
	@Override
	public List<String> batchUploadFile(List<MultipartFile> multipartFileList) {
		List<String> urlList = new ArrayList<>();
		for (MultipartFile multipartFile : multipartFileList) {
			urlList.add(this.uploadSingleFile(multipartFile, null));
		}
		return urlList;
	}

	/**
	 * 文件上传
	 * @param multipartFile
	 * @return
	 */
	@Override
	public String uploadFile(MultipartFile multipartFile) {
		return this.uploadSingleFile(multipartFile, null);
	}

	/**
	 * 文件上传
	 * @param multipartFile
	 * @param directory 存放目录
	 * @return
	 */
	@Override
	public String uploadFile(MultipartFile multipartFile, String directory) {
		return this.uploadSingleFile(multipartFile, directory);
	}

	/**
	 * 七牛云服务图片上传【上传到七牛云中】
	 * @param multipartFile
	 * @param directory 目录
	 * @return
	 */
	private String uploadSingleFile(MultipartFile multipartFile, String directory) {
		String url = "";
		try {
			// 从Redis中获取系统配置
			SystemConfig systemConfig = systemConfigService.getConfig();
			url = systemConfig.getQiNiuPictureBaseUrl() + qiniuUtil.uploadQiniu(multipartFile, systemConfig, directory);
		} catch (Exception e) {
			e.getStackTrace();
			log.error("文件上传七牛云失败: {}", e.getMessage());
		}
		return url;
	}

	/**
	 * 文件删除
	 * @param key
	 */
	@Override
	public void deleteFile(String key) {
		try {
			// 从Redis中获取系统配置
			SystemConfig systemConfig = systemConfigService.getConfig();
			qiniuUtil.deleteQiniu(key, systemConfig);
		} catch (Exception e) {
			e.getStackTrace();
			log.error("七牛云文件删除失败: {}", e.getMessage());
		}
	}

	/**
	 * 文件批量删除
	 * @param keyList
	 */
	@Override
	public void batchDeleteFile(String[] keyList) {
		try {
			// 从Redis中获取系统配置
			SystemConfig systemConfig = systemConfigService.getConfig();
			qiniuUtil.batchDelete(keyList, systemConfig);
		} catch (Exception e) {
			e.getStackTrace();
			log.error("七牛云文件批量删除失败: {}", e.getMessage());
		}
	}
}
